package com.itheima.aspect;

import com.alibaba.fastjson.JSON;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * 系统日志的切面类
 *
 * @author liudo
 * @version 1.0
 * @project tlias-backend
 * @date 2023/9/13 15:20:44
 */
@Component
@Aspect
public class SysLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Pointcut("@annotation(com.itheima.annotation.SysLog)")
    public void pt() {

    }

    @Around("pt()")
    public Object sysLog(ProceedingJoinPoint joinPoint) throws Throwable {
        // 操作人
        String token = httpServletRequest.getHeader("Token");
        Claims body = Jwts.parser()
                .setSigningKey("itheima")
                .parseClaimsJws(token)
                .getBody();
        Integer userId = body.get("userId", Integer.class);
        // 执行方法的全类名
        String className = joinPoint.getTarget().getClass().getName();
        // 执行方法名
        String methodName = joinPoint.getSignature().getName();
        // 方法运行时参数
        Object[] args = joinPoint.getArgs();
        // 方法执行时长
        long start = System.currentTimeMillis();
        Object o = joinPoint.proceed();
        long end = System.currentTimeMillis();

        // 写进数据库
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateUser(userId);
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(className);
        operateLog.setMethodName(methodName);
        operateLog.setMethodParams(Arrays.toString(args));
        operateLog.setReturnValue(JSON.toJSONString(o));
        operateLog.setCostTime(end - start);
        operateLogMapper.insert(operateLog);
        return o;
    }
}
